package com.example.springbootlearn.controller;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.example.springbootlearn.annotation.TestOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * @Author libo
 * @Date 2023/2/27 21:51
 */

@Slf4j
@RequestMapping("test")
@RestController
public class TestCallBackController {

    // 每次发送的数据大小 1280 字节
    private static final int CHUNCKED_SIZE = 1280;

    @GetMapping("callback")
    public String S() {
        return HttpUtil.get("http://localhost:9990/login/cas?ticket=ticket_we9ch");
    }

    @GetMapping("order")
    public String order() {
        Map<String, Object> beansWithAnnotation = SpringUtil.getApplicationContext().getBeansWithAnnotation(TestOrder.class);

        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            TestOrder annotation = entry.getValue().getClass().getAnnotation(TestOrder.class);
            System.out.println(entry.getKey() + " 的value值为 " + annotation.value());
        }

        List<Object> collect = beansWithAnnotation.values()
                .stream()
                .sorted(Comparator.comparing(x -> x.getClass().getAnnotation(TestOrder.class).value()))
                .collect(toList());
        return "ss";
    }

    @PostMapping("upload")
    public String upload(@RequestParam(value = "file") MultipartFile file) throws IOException, InterruptedException {

        InputStream input = file.getInputStream();

        byte[] bytes = new byte[CHUNCKED_SIZE];
        int len = -1;
        long lastTs = 0;
        System.out.println("消息长度为" + len);
        while ((len = input.read(bytes)) != -1) {

            if (len < CHUNCKED_SIZE) {
                log.info("len长度{}", len);
                sendByte(bytes = Arrays.copyOfRange(bytes, 0, len));
                break;
            }

            long curTs = System.currentTimeMillis();
            if (lastTs == 0) {
                lastTs = System.currentTimeMillis();
            } else {
                long s = curTs - lastTs;
                if (s < 40) {
                    System.out.println("error time interval: " + s + " ms");
                }
            }

//            send(client, Arrays.copyOfRange(bytes, 0, len));
            sendByte(bytes);
            // 每隔40毫秒发送一次数据
            Thread.sleep(40);
        }

        return "success";

    }

    private void sendByte(byte[] bytes) {
        System.out.println(bytes.length);
    }
}
